package net.bat.service.account;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

public class CKFormAuthenticationFilter extends FormAuthenticationFilter {
	static final String COOKIE_UNAME = "uname";

	/*
	 * 
	 * 主要是针对登入成功的处理方法。对于请求头是AJAX的之间返回JSON字符串。
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.addCookie(new Cookie(COOKIE_UNAME, (String) token.getPrincipal()));
		return super.onLoginSuccess(token, subject, request, httpServletResponse);
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		// setFailureAttribute(request, e);
		// login failed, let request continue back to the login page:
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		Cookie ck = new Cookie(COOKIE_UNAME, null);
		ck.setMaxAge(0);
		httpServletResponse.addCookie(ck);
		return super.onLoginFailure(token, e, request, httpServletResponse);
	}

	@Override
	protected void cleanup(ServletRequest request, ServletResponse response, Exception existing)
			throws ServletException, IOException {
		super.cleanup(request, response, existing);
	}
}
